package com.example.nuc_ms_beta.ui.viewconstruction.mainfragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.example.nuc_ms_beta.R;
import com.example.nuc_ms_beta.app.MyApplication;
import com.example.nuc_ms_beta.bean.videofragment.Video;
import com.example.nuc_ms_beta.ui.activity.VideoActivity;
import com.example.nuc_ms_beta.ui.viewconstruction.adapter.VideoListViewAdapter;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;


/**
 * Created by 张博川 on 2016/9/2.
 */
public class VideoFragment extends Fragment {
    private Context context;
    private View view;
    private LayoutInflater inflater;
    private GridView videofragment_gv;


    public VideoFragment(Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initView(container);
        return view;
    }

    private void initView(ViewGroup container) {
        this.view = inflater.inflate(R.layout.videofragmentlayout, container, false);
        videofragment_gv = (GridView) view.findViewById(R.id.videofragment_gv);
        quertData();
    }

    private void quertData() {
        BmobQuery<Video> query_listView_video = new BmobQuery<>();
        query_listView_video.findObjects(new FindListener<Video>() {

            @Override
            public void done(final List<Video> list, BmobException e) {
                if (e == null) {
                    videofragment_gv.setAdapter(new VideoListViewAdapter(getContext(), list, R.layout.fragment_video_itme));
                    videofragment_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent videoPlayerIntent = new Intent(getContext(), VideoActivity.class);
                            videoPlayerIntent.putExtra("url", list.get(position).getUrl());
                            startActivity(videoPlayerIntent);
                        }
                    });
                } else {
                    Log.d(MyApplication.TAG, e.getErrorCode() + " " + e.getMessage());
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}
